/**
 * 页面状态缓存管理
 */

class PageCache {
    constructor() {
        this.storageKey = 'pod_image_composer_cache';
        this.cache = this.loadCache();
    }
    
    loadCache() {
        try {
            const cached = localStorage.getItem(this.storageKey);
            return cached ? JSON.parse(cached) : {};
        } catch (e) {
            console.error('加载缓存失败:', e);
            return {};
        }
    }
    
    saveCache() {
        try {
            localStorage.setItem(this.storageKey, JSON.stringify(this.cache));
        } catch (e) {
            console.error('保存缓存失败:', e);
        }
    }
    
    // 保存页面状态
    savePage(pageKey, state) {
        this.cache[pageKey] = {
            ...state,
            timestamp: Date.now()
        };
        this.saveCache();
    }
    
    // 获取页面状态
    getPage(pageKey) {
        const cached = this.cache[pageKey];
        if (!cached) return null;
        
        // 检查缓存是否过期（24小时）
        const maxAge = 24 * 60 * 60 * 1000;
        if (Date.now() - cached.timestamp > maxAge) {
            delete this.cache[pageKey];
            this.saveCache();
            return null;
        }
        
        return cached;
    }
    
    // 清除特定页面缓存
    clearPage(pageKey) {
        delete this.cache[pageKey];
        this.saveCache();
    }
    
    // 清除所有缓存
    clearAll() {
        this.cache = {};
        this.saveCache();
    }
}

// 全局缓存实例
window.PAGE_CACHE = new PageCache();

// 定制编辑器缓存管理
class CustomizeEditorCache {
    constructor(editor) {
        this.editor = editor;
        this.pageKey = 'customize_editor';
        this.autoSaveInterval = null;
    }
    
    // 启动自动保存
    startAutoSave() {
        // 每30秒自动保存状态
        this.autoSaveInterval = setInterval(() => {
            this.saveState();
        }, 30000);
        
        // 页面卸载时保存
        window.addEventListener('beforeunload', () => {
            this.saveState();
        });
    }
    
    // 停止自动保存
    stopAutoSave() {
        if (this.autoSaveInterval) {
            clearInterval(this.autoSaveInterval);
            this.autoSaveInterval = null;
        }
    }
    
    // 保存当前状态
    saveState() {
        if (!this.editor) return;
        
        const state = {
            currentTemplate: this.editor.currentTemplate,
            elements: this.editor.elements.map(element => ({
                id: element.id,
                imageUrl: element.imageUrl,
                regionIndex: element.regionIndex,
                elementIndex: element.elementIndex,
                x: element.x,
                y: element.y,
                width: element.width,
                height: element.height,
                scaleX: element.scaleX,
                scaleY: element.scaleY,
                rotation: element.rotation
            })),
            selectedElementId: this.editor.selectedElement ? this.editor.selectedElement.id : null,
            projectId: this.editor.projectId,
            projectName: $('#projectName').val(),
            templateId: $('#templateSelect').val()
        };
        
        window.PAGE_CACHE.savePage(this.pageKey, state);
    }
    
    // 恢复状态
    restoreState() {
        const state = window.PAGE_CACHE.getPage(this.pageKey);
        if (!state || !this.editor) return false;
        
        try {
            // 恢复模板
            if (state.currentTemplate && state.templateId) {
                $('#templateSelect').val(state.templateId);
                this.editor.currentTemplate = state.currentTemplate;
            }
            
            // 恢复元素
            if (state.elements && state.elements.length > 0) {
                this.editor.elements = state.elements.map(elementData => ({
                    ...elementData,
                    image: null,
                    loaded: false
                }));
                
                // 重新加载图片
                this.editor.elements.forEach(element => {
                    this.editor.loadElementImage(element);
                });
            }
            
            // 恢复项目信息
            if (state.projectId) {
                this.editor.projectId = state.projectId;
            }
            if (state.projectName) {
                $('#projectName').val(state.projectName);
            }
            
            // 恢复选中状态
            if (state.selectedElementId) {
                this.editor.selectedElement = this.editor.elements.find(el => el.id === state.selectedElementId);
            }
            
            // 更新界面
            this.editor.updateLayersList();
            this.editor.updatePropertiesPanel();
            this.editor.renderCanvas();
            
            return true;
        } catch (e) {
            console.error('恢复状态失败:', e);
            return false;
        }
    }
    
    // 清除缓存
    clearCache() {
        window.PAGE_CACHE.clearPage(this.pageKey);
    }
}

// 导出缓存管理器
window.CustomizeEditorCache = CustomizeEditorCache;
